﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using Clarendon.AzureBilling.Gui.AzureServices;
using Clarendon.AzureBilling.Library;
using IBillingContractCallback = Clarendon.AzureBilling.Library.IBillingContractCallback;

namespace Clarendon.AzureBilling.Gui
{
    [CallbackBehavior(ConcurrencyMode = ConcurrencyMode.Reentrant)]
    public class BillingContractCallback : AzureServices.IBillingContractCallback
    {
        private readonly AzureServices.BillingContractClient _client = null;

        public BillingContractCallback()
        {
            var ctx = new InstanceContext(this);
            _client = new BillingContractClient(ctx);
            _client.Open();
        }

        internal void Subscribe()
        {
            _client.ObserveServiceBillingContract();
        }

        internal void Unsubscribe()
        {
            _client.UnobserveServiceBillingContract();
        }

        internal List<HostedService> SyncRequestServices()
        {
            return _client.MakeAdHocServiceRequest().ToList();
        }

        public void ServiceDetails(HostedService[] services)
        {
            var myWindow = App.Current.MainWindow;
            myWindow.Dispatcher.BeginInvoke(
            (Action)(() =>
            {
                // enumerate the hosted services and then add them one by one to the treeview
                foreach (var hostedService in services)
                {
                    string location = String.IsNullOrEmpty(hostedService.Location) ? "N/A" : hostedService.Location;
                    var item = new TreeViewItem
                    {
                        Name = hostedService.Name,
                        Header = String.Format("{0} ({1})", hostedService.Name, location)
                    };
                    var itemServices = (TreeViewItem)((MainWindow)myWindow).tvHostedServices.Items.GetItemAt(0);
                    itemServices.Items.Add(item);
                }
            }));
        }
    }
}
